package com.hk.web.core.advice;

import com.hk.commons.eunms.SysCode;
import com.hk.commons.exceptions.BaseException;
import com.hk.commons.exceptions.BusinessException;
import com.hk.commons.exceptions.WebException;
import com.hk.commons.vo.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.List;

/**
 * 配置全局的异常通知
 */
@RestControllerAdvice
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    public JsonResult handleBindException(Exception e) {
        logger.error("参数验证异常", e);
        BindingResult result;
        if (e instanceof BindException) {
            result = ((BindException) e).getBindingResult();
        } else {
            result = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        StringBuilder msgSB = new StringBuilder();
        List<ObjectError> allErrors = result.getAllErrors();
        int size = allErrors.size();
        int offset = size -1;
        for (int i = 0; i < size; i++) {
            ObjectError errorObj = allErrors.get(i);
            msgSB.append(errorObj.getDefaultMessage());
            if (i != offset){
                msgSB.append(";");
            }
        }
        return new JsonResult(SysCode.PARAM_ERROR, null, new Object[]{msgSB.toString()});
    }

    @ExceptionHandler({HttpClientErrorException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public JsonResult httpClientErrorException(HttpClientErrorException e) {
        logger.error("RestClient访问异常", e);
        return new JsonResult(SysCode.REST_AUTH_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public JsonResult handleSQLException(HttpServletRequest request, Exception e) {
        logger.error("系统异常", e);
        return new JsonResult(SysCode.SYS_ERROR);
    }

    @ExceptionHandler({BusinessException.class,WebException.class})
    public JsonResult handleBusinessException(HttpServletRequest request, BaseException e) {
        logger.error("系统异常", e);
        return new JsonResult(e.getErrorEnums());
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public JsonResult handleBusinessException(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        String method = request.getMethod();
        String str = "[{0}]请求不支持";
        String format = MessageFormat.format(str, method);
        logger.error(format);
        return new JsonResult("99999",null, format);
    }

}
